package com.br.android.widingwheels;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuInflater;
import com.br.android.widingwheels.adapter.ListaCategoriasAdapter;
import com.br.android.widingwheels.adapter.ListaGastosAdapter;
import com.br.android.widingwheels.db.WidingWheelsCursor;
import com.br.android.widingwheels.db.WidingWheelsDAO;
import com.br.android.widingwheels.entidades.Gasto;
import com.br.android.widingwheels.maps.MapGastosActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class PrincipalActivity extends SherlockFragmentActivity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	
	public static double totalValorGastos;
	public static WidingWheelsDAO dao;
	public static WidingWheelsCursor cursor;
	
	public static List<Gasto> listGastos;
	public static List<Gasto> listGastosPorCategoria;
	public static ListaGastosAdapter adapterGastos;
	public static ListaCategoriasAdapter adapterCategorias;
	
	Currency currency = Currency.getInstance(Locale.getDefault());
	private static DecimalFormat format;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_principal);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());
		
		format = new DecimalFormat(currency.getSymbol() + " ###,###,##0.00");

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		
		dao = new WidingWheelsDAO(this);
		cursor = dao.getTotalValores();
		totalValorGastos = cursor.getTotalSomaValores();
		
		listGastos = new ArrayList<Gasto>();
		cursor = dao.getAll();
		for(int i = 0; i < cursor.getCount(); i++){
			cursor.moveToPosition(i);
			Gasto g = new Gasto();
			g.setIdGasto(cursor.getIdGasto());
			g.setNomeGasto(cursor.getNomeGasto());
			g.setCategoriaGasto(cursor.getCategoriaGasto());
			g.setValorGasto(cursor.getValorGasto());
			g.setDataGasto(cursor.getDataGasto());
			g.setLatitudeGasto(cursor.getLatitudeGasto());
			g.setLongitudeGasto(cursor.getLongitudeGasto());
			g.setNomeLocal(cursor.getNomeLocalGasto());
			listGastos.add(g);
		}
		
		listGastosPorCategoria = new ArrayList<Gasto>();
		cursor = dao.getTotalValoresPorCategoria();
		for(int i = 0; i < cursor.getCount(); i++){
			cursor.moveToPosition(i);
			Gasto g = new Gasto();
			g.setCategoriaGasto(cursor.getCategoriaGasto());
			g.setValorGasto(cursor.getSomaPorCategoria());
			listGastosPorCategoria.add(g);
		}
		
		adapterGastos = new ListaGastosAdapter(this, listGastos);
		adapterCategorias = new ListaCategoriasAdapter(this, listGastosPorCategoria);
		
		dao.close();
		cursor.close();
		
		mViewPager.setCurrentItem(1);
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_principal, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuAdicionarGasto:
			startActivity(new Intent(this, AdicionarGastoActivity.class));
			overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
			finish();
			break;
		case R.id.menuMapa:
			startActivity(new Intent(this, MapGastosActivity.class));
			overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			Fragment fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return getString(R.string.titulo_categorias).toUpperCase();
			case 1:
				return getString(R.string.titulo_gasto).toUpperCase();
			}
			return null;
		}
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = null;
			if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
				view = inflater.inflate(R.layout.layout_principal_lista_categorias, null);
				TextView textViewTotal = (TextView) view.findViewById(R.id.textViewValorTotalGastosPorCategoria);
				textViewTotal.setText("Total: " + format.format(totalValorGastos));
				
				ListView listViewCategorias = (ListView) view.findViewById(R.id.listViewGastosPorCategoria);
				listViewCategorias.setAdapter(adapterCategorias);
			}
			if(getArguments().getInt(ARG_SECTION_NUMBER) == 2){
				view = inflater.inflate(R.layout.layout_principal_lista_gasto, null);
				TextView textViewTotal = (TextView) view.findViewById(R.id.textViewValorTotalGastos);
				textViewTotal.setText("Total: " + format.format(totalValorGastos));
				
				ListView listViewGastos = (ListView) view.findViewById(R.id.listViewGastos);
				listViewGastos.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> av, View v, int position, long id) {
						final Gasto g = listGastos.get(position);
						Intent intent = new Intent(getActivity(), ExibicaoGastoActivity.class);
						intent.putExtra("idgasto", g.getIdGasto());
						intent.putExtra("descricao", g.getNomeGasto());
						intent.putExtra("valor", g.getValorGasto());
						intent.putExtra("data", g.getDataGasto());
						intent.putExtra("categoria", g.getCategoriaGasto());
						startActivity(intent);
						getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
						getActivity().finish();
					}
				});
				listViewGastos.setAdapter(adapterGastos);
			}
			return view;
					
		}
		
		public void excluirGasto(final Gasto g){
			AlertDialog.Builder dialogExcluir = new AlertDialog.Builder(getActivity());
			dialogExcluir.setTitle("Widing Wheels");
			dialogExcluir.setMessage("Tem certeza que deseja excluir esse gasto?");
			dialogExcluir.setPositiveButton("Excluir", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dao.excluirGasto(g.getIdGasto());
					listGastos.remove(g);
					adapterGastos.notifyDataSetChanged();
					cursor = dao.getTotalValores();
					totalValorGastos = cursor.getTotalSomaValores();
					dialog.dismiss();
				}
			});
			dialogExcluir.setNegativeButton("Cancelar", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			dialogExcluir.show();
		}
	}

}
